/******************************************************************************
* mover event study
*****************************************************************************/


*load cut version to get varlist
use "${dataRoot}/tu_mover_delta${ext}_cut.dta", clear
labelVars 0 0

describe



**** mover data (load one variable at a time)
foreach var of varlist $keyMvVars{
	
	use num_mv - ${Geo}_d numobs *`var'* asofy - rank using "${dataRoot}/tu_mover_delta${ext}.dta", clear

	describe 
	
	sum rel_q
	global refq     = -`r(min)'
	
	*fill delta pre/post BAPCPA based on calendar time
	gen bapcpa = asofy<2006
	bysort varID bapcpa: egen delta_`var'_cust_bapcpa = mean(delta_`var')
	
	
	* just need movers for event study regression
	qui keep if num_mv==1 
	
	* keep movers with matched non-movers so we can compute delta
	qui keep if delta_`var'_cust!=.
	
	* movers with sufficient observations pre and post move
	qui keep if min_rel_q<=-${evtQ} & max_rel_q>=${evtQ} & max_rel_q!=.	
	
	*movers who moved prior to 2008
	keep if move_t<200800
	
	* restrict to relative event time of interest
	qui keep if rel_q>=-${evtQpre} & rel_q<=${evtQpost}
	
	
		
	*** merge with origin/destination state
	if $evt_xst==1{
		rename cz cz0
			
		rename cz_o cz
		*merge with cz - state crosswalk
		merge m:1 cz using "${proj}/Data/Crosswalk/cz_name", keep(3) nogen
		rename statefip state_o
		rename cz cz_o

		rename cz_d cz
		*merge with cz - state crosswalk
		merge m:1 cz using "${proj}/Data/Crosswalk/cz_name", keep(3) nogen
		rename statefip state_d
		rename cz cz_d
			
		rename cz0 cz

		***
		gen with_st = state_o==state_d
		tab with_st	if rel_q==0
	}
	
	
	* credit score tertile the quarter prior to move
	if $evt_score==1{
		sum score [w=numobs] if rel_q==-1, d
		xtile id_score_tertile = score  [fw=numobs] if rel_q==-1, nq(3)
		
		tab id_score_tertile
		sum score if id_score_tertile==1
		sum score if id_score_tertile==2
		sum score if id_score_tertile==3
		
		bysort varID: egen score_tertile = mean(id_score_tertile)
	}
	
	
	*********************************************************************
	//binned scatter plots and pre-trend plots
	*********************************************************************
	*compared mover individual change in outcome vs delta
	di "running `var'"
	labelVars 1 0

		
	*plot histogram of delta (Figure A9,A8,A11)
	if $run_hist==1{
		qui sum delta_`var' [fw=numobs]
		local u 	= `r(mean)'
		local sigma = `r(sd)'
		local u_str = string(`u', "%9.1fc")
		local s_str = string(`sigma', "%9.1fc")
		
		local bin = 8*`sigma'/40
		
		twoway (hist delta_`var' ///
				if inrange(delta_`var', -4*`sigma', 4*`sigma') [fw=numobs], percent width(`bin')  ///
			title("mean = `u_str'" "sd = `s_str'", position(1) ring(0) size(medium)) ///
			graphregion(fcolor(white)) xtitle("Size of Move in `:var l `var''"))
		graph export "${figGeoDebt}/hist_Delta_truncate${ext}_`var'.pdf", replace
	}

	
	*pre-trend binned scatters (Figure 2,3)
	if $run_binscatter==1{
		preserve	
			
			*ventile of delta (egen mean will populate delta for matched non-movers)
			xtile ventile = delta_`var'  [fw=numobs], nq(${nBins})
			bysort varID: egen ventile_cust = mean(ventile) 
			
			*pre/post level for movers/non-movers	
			qui gen pre_      = `var' if num_mv==1 & rel_q==${binsPre} 
			qui gen pre_late  = `var' if num_mv==1 & rel_q==${binsPre2} 
			qui gen post_	  = `var' if num_mv==1 & rel_q==${binsPost} 	
			
			
			*collapse to each ventile
			local textvar = "`:var l `var''"
			
			*collapse to each varID		
			collapse (min) pre_* post_* delta_`var' ventile_cust numobs, by(varID) fast
			
			gen rsp      = post_-pre_		   if ventile_cust<=${nBins}
			gen preMv    = pre_late - pre_     if ventile_cust<=${nBins}		
			
			
			reg rsp delta_`var'   [fw=numobs]
			figShowSlope rsp delta_`var' "Rsp" ""		
			
			reg preMv delta_`var' [fw=numobs]
			figShowSlope preMv delta_`var' "Pret" ""
			
			
			*collapse to each ventile for plot
			collapse pre_* post_* rsp* preMv delta_`var' [fw=numobs], by(ventile_cust) fast
			drop if ventile_cust ==.
			
			
			*save temp data
			compress
			save "${outDataDir}/bs_delta_mv0407_`var'${ext}.dta", replace



			*set axis range locals			
			local var ccdqy3
			symXYaxis delta_`var' rsp

			
			*impose y-axis scale
			if "`var'"=="bkrt13y3"{
				local ysc = "-10(5)5"
			}				
			if "`var'"=="bkrt7y3"{
				local ysc = "-15(5)0"
			}
			if "`var'"=="ccdq"{
				local ysc = "-4(2)0"
			}
			if "`var'"=="ccdq_cond"{
				local ysc = "-6(2)0"
			}
			if "`var'"=="ccdqy1"{
				local ysc = "0(1)3"
			}
			if "`var'"=="ccdqy3"{
				local ysc = "-2(1)2"
			}
			if "`var'"=="unpdcol"{
				local ysc = "1(2)7"
			}
			if "`var'"=="unpdcoly1"{
				local ysc = "1(2)9"
			}
			if "`var'"=="unpdcoly3"{
				local ysc = "1(2)9"
			}
			if "`var'"=="colmed"{
				local ysc = "0(2)10"
			}
			if "`var'"=="colexmed"{
				local ysc = "-5(1)1"
			}

			*no mark for non-mover
			twoway (scatter rsp delta_`var' , ///
					yscale(range(`ysc')) ylabel(`ysc')       ///
					xscale(range(-${xlbl}(${xstep})${xlbl})) xlabel(-${xlbl}(${xstep})${xlbl}) ) ///
				   (lfit rsp delta_`var') ,     ///
					graphregion(fcolor(white))       ///
					xtitle("Size of Move") ///
					ytitle("Pre-Post Change in `textvar'")                  ///
					title("${figShowSlopeRsp}", position(11) ring(0) size(medium)) legend(off)
			graph export "${figGeoDebt}/delta_mvrVplace${ext}_m47_b${nBins}_`var'.pdf", replace	
			
			
			
			*2) pre-trend mover: early - late		
			symXYaxis delta_`var' preMv 
			
			*impose y-axis scale
			if "`var'"=="bkrt13y3"{
				local ysc = "-15(5)5"
			}			
			if "`var'"=="bkrt7y3"{
				local ysc = "-15(5)10"
			}
			if "`var'"=="ccdq"{
				local ysc = "-5(1)1"
			}
			if "`var'"=="ccdq_cond"{
				local ysc = "-5(1)1"
			}
			if "`var'"=="ccdqy1"{
				local ysc = "-5(1)1"
			}
			if "`var'"=="ccdqy3"{
				local ysc = "-6(1)0"
			}
			if "`var'"=="unpdcol"{
				local ysc = "-1(1)3"
			}
			if "`var'"=="unpdcoly1"{
				local ysc = "-2(1)3"
			}
			if "`var'"=="unpdcoly3"{
				local ysc = "-3(1)3"
			}
			if "`var'"=="colmed"{
				local ysc = "-1(1)4"
			}
			if "`var'"=="colexmed"{
				local ysc = "-3(1)2"
			}
			
			
			twoway (scatter preMv delta_`var', ///
					yscale(range(`ysc')) ylabel(`ysc')       ///
					xscale(range(-${xlbl}(${xstep})${xlbl})) xlabel(-${xlbl}(${xstep})${xlbl}) )     ///
					(lfit preMv delta_`var') , ///
					graphregion(fcolor(white))         ///
					xtitle("Size of Move") ///
					ytitle("Pre-Move Change in `textvar'")    ///
					title("${figShowSlopePret}", position(11) ring(0) size(medium)) legend(off) 
			graph export "${figGeoDebt}/delta_mvr_prepreTrend${ext}_m47_b${nBins}_`var'.pdf", replace
			
		restore	 
	}
	
	*********************************************************************
	//event study regression (Figure 4, A12, A14)
	*********************************************************************
	
	
	if $run_event_study==1{
	
		*base quarter to set coefficient at 0
		global refqbase=${refq}-1
		labelVars 1 0
		sum `var'
		
		
		*CZ pair
		gen od_cz = cz_o*100000 + cz_d
		
		* year of move
		gen move_y = floor(move_t/100)
		

// 		** dummies in the function:
// 		run base
// 		positive vs negative move, 
// 		young vs old at move (40 cut-off),
// 		within state vs across states
// 		geo origin/destination X event time
// 		whether we separate by movers cohort (pre vs post bapcpa)
//		by credit score tercile
// 		remake using stored data

		* separate movers in each cohort
		if $evt_sample_version==0{
			genEventReg `var' "sub${evtQ}_m47"  "-${evtQpre} , ${evtQpost}"  "-${evtQpre}(${evtQstep})${evtQpost}" $evt_base $evt_posneg $evt_age $evt_xst $evt_od_fe $evt_cohort $evt_score $evt_remake
		}
		else{
			genEventReg `var' "sub${evtQ}"  "-${evtQpre} , ${evtQpost}"  "-${evtQpre}(${evtQstep})${evtQpost}" $evt_base $evt_posneg $evt_age $evt_xst $evt_od_fe $evt_cohort $evt_score $evt_remake
		}
		
		*close all graph windows
		*window manage close graph _all
		
	
	}
}



















